// pointsStore.ts - 积分管理工具
import { ref } from 'vue'
import { getCurrentUser, getUserId } from './userStore'
import { addCoupon } from './couponStore'

// 积分记录接口
export interface PointsRecord {
  id: string
  type: 'earn' | 'spend'
  amount: number
  source: string
  description: string
  createTime: string
}

// 积分商品接口
export interface PointsProduct {
  id: string
  name: string
  description: string
  pointsCost: number
  couponAmount: number
  minAmount: number
  image: string
  stock: number
}

const userPoints = ref(0) // 可用积分（用于商城消费）
const memberPoints = ref(0) // 会员积分（基于运动时长，只增不减）
const pointsRecords = ref<PointsRecord[]>([])

// 积分商城商品
const pointsProducts: PointsProduct[] = [
  {
    id: 'points_product_001',
    name: '5元优惠券',
    description: '满30元可用',
    pointsCost: 50,
    couponAmount: 5,
    minAmount: 30,
    image: '🎫',
    stock: 999
  },
  {
    id: 'points_product_002',
    name: '10元优惠券',
    description: '满60元可用',
    pointsCost: 100,
    couponAmount: 10,
    minAmount: 60,
    image: '🎟️',
    stock: 999
  },
  {
    id: 'points_product_003',
    name: '20元优惠券',
    description: '满120元可用',
    pointsCost: 200,
    couponAmount: 20,
    minAmount: 120,
    image: '🎪',
    stock: 999
  },
  {
    id: 'points_product_004',
    name: '50元优惠券',
    description: '满300元可用',
    pointsCost: 500,
    couponAmount: 50,
    minAmount: 300,
    image: '🏆',
    stock: 999
  }
]

// 获取用户积分
export function getUserPoints(): number {
  return userPoints.value
}

// 获取会员积分（用于会员卡显示和等级判断）
export function getMemberPoints(): number {
  return memberPoints.value
}

// 获取积分记录
export function getPointsRecords(): PointsRecord[] {
  return pointsRecords.value
}

// 获取积分商城商品
export function getPointsProducts(): PointsProduct[] {
  return pointsProducts
}

// 添加积分
export function addPoints(amount: number, source: string, description: string): boolean {
  try {
    userPoints.value += amount
    
    const record: PointsRecord = {
      id: `points_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
      type: 'earn',
      amount,
      source,
      description,
      createTime: new Date().toISOString()
    }
    
    pointsRecords.value.unshift(record)
    saveUserPoints()
    
    console.log(`积分增加: +${amount}, 当前积分: ${userPoints.value}`)
    return true
  } catch (error) {
    console.error('添加积分失败:', error)
    return false
  }
}

// 消费积分
export function spendPoints(amount: number, source: string, description: string): boolean {
  try {
    if (userPoints.value < amount) {
      console.warn('积分不足')
      return false
    }
    
    userPoints.value -= amount // 只减少可用积分
    // memberPoints.value 保持不变
    
    const record: PointsRecord = {
      id: `points_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
      type: 'spend',
      amount,
      source,
      description,
      createTime: new Date().toISOString()
    }
    
    pointsRecords.value.unshift(record)
    saveUserPoints()
    
    console.log(`积分消费: -${amount}, 可用积分: ${userPoints.value}, 会员积分: ${memberPoints.value}`)
    return true
  } catch (error) {
    console.error('消费积分失败:', error)
    return false
  }
}

// 根据运动时间添加积分（每10分钟1分）
export function addPointsForExercise(exerciseMinutes: number): number {
  const pointsEarned = Math.floor(exerciseMinutes / 10)
  if (pointsEarned > 0) {
    // 同时增加可用积分和会员积分
    userPoints.value += pointsEarned
    memberPoints.value += pointsEarned
    
    const record: PointsRecord = {
      id: `points_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
      type: 'earn',
      amount: pointsEarned,
      source: '运动奖励',
      description: `运动${exerciseMinutes}分钟，获得${pointsEarned}积分`,
      createTime: new Date().toISOString()
    }
    
    pointsRecords.value.unshift(record)
    saveUserPoints()
    
    console.log(`运动积分增加: +${pointsEarned}, 可用积分: ${userPoints.value}, 会员积分: ${memberPoints.value}`)
  }
  return pointsEarned
}

// 兑换积分商品
export function exchangePointsProduct(productId: string): boolean {
  try {
    const product = pointsProducts.find(p => p.id === productId)
    if (!product) {
      console.error('商品不存在')
      return false
    }
    
    if (userPoints.value < product.pointsCost) {
      console.warn('积分不足')
      return false
    }
    
    // 消费积分
    const success = spendPoints(product.pointsCost, '积分兑换', `兑换${product.name}`)
    if (!success) {
      return false
    }
    
    // 添加优惠券
    const futureDate = new Date()
    futureDate.setMonth(futureDate.getMonth() + 1) // 1个月后过期
    
    addCoupon({
      name: product.name,
      amount: product.couponAmount,
      minAmount: product.minAmount,
      type: 'cash',
      status: 'available',
      expireDate: futureDate.toISOString().slice(0, 10),
      description: product.description,
      source: '积分兑换'
    })
    
    console.log(`成功兑换${product.name}`)
    return true
  } catch (error) {
    console.error('兑换失败:', error)
    return false
  }
}

// 加载用户积分数据
export function loadUserPoints(): void {
  try {
    const userId = getUserId()
    const pointsKey = `userPoints_${userId}`
    const memberPointsKey = `memberPoints_${userId}`
    const recordsKey = `pointsRecords_${userId}`
    
    const storedPoints = localStorage.getItem(pointsKey)
    const storedMemberPoints = localStorage.getItem(memberPointsKey)
    const storedRecords = localStorage.getItem(recordsKey)
    
    if (storedPoints) {
      userPoints.value = parseInt(storedPoints) || 0
    }
    
    if (storedMemberPoints) {
      memberPoints.value = parseInt(storedMemberPoints) || 0
    }
    
    if (storedRecords) {
      pointsRecords.value = JSON.parse(storedRecords) || []
    }
    
    console.log('积分数据加载完成:', { 
      availablePoints: userPoints.value, 
      memberPoints: memberPoints.value, 
      records: pointsRecords.value.length 
    })
  } catch (error) {
    console.error('加载积分数据失败:', error)
    userPoints.value = 0
    memberPoints.value = 0
    pointsRecords.value = []
  }
}

// 保存用户积分数据
export function saveUserPoints(): void {
  try {
    const userId = getUserId()
    const pointsKey = `userPoints_${userId}`
    const memberPointsKey = `memberPoints_${userId}`
    const recordsKey = `pointsRecords_${userId}`
    
    localStorage.setItem(pointsKey, userPoints.value.toString())
    localStorage.setItem(memberPointsKey, memberPoints.value.toString())
    localStorage.setItem(recordsKey, JSON.stringify(pointsRecords.value))
  } catch (error) {
    console.error('保存积分数据失败:', error)
  }
}

// 获取积分统计
export function getPointsStats() {
  const totalEarned = pointsRecords.value
    .filter(r => r.type === 'earn')
    .reduce((sum, r) => sum + r.amount, 0)
    
  const totalSpent = pointsRecords.value
    .filter(r => r.type === 'spend')
    .reduce((sum, r) => sum + r.amount, 0)
    
  return {
    current: userPoints.value, // 当前可用积分
    member: memberPoints.value, // 会员积分
    totalEarned,
    totalSpent,
    recordsCount: pointsRecords.value.length
  }
}